/**
 * Created by 蔡岳衡 on 2016/8/22.
 */

var database = function () {

    var action = path + '/action/powerdb/designer/';
    var url = action + 'database/';

    //数据库表格
    var databaseTableSeletor = '#databaseJqgridTable';
    var databasePagerSeletor = '#databaseJqgridPager';
    var databaseSearchFormSeletor = '#databaseSearchForm';

    //新增修改弹窗
    var databaseAddModalSelector = '#databaseAddModal';
    var databaseAddOrEditFormSelector = '#databaseAddOrEditForm';

    /** 枚举关键字定义 */
    var enums = ['pdm_database-databaseCode'];

    /** 获取所有需要翻译的枚举 */
    var enumMap = sPost.getEnumMap(enums);

    var dbGridSetting = {
        gridId: databaseTableSeletor,
        pagerId: databasePagerSeletor,
        gridHeightType: 1,
        datatype: 'local',
        data: [],
        url: null,
        mtype: "post",
        multiselect: false,
        rownumbers: true,
        autowidth: true,
        rowNum: 15,
        rowList: [15, 20, 30],
        colNames: ['id', '创建人id', '数据库名', '中文名', '编码', '创建人', '修改人', '创建时间', '修改时间', '描述'],
        colModel: [
            {name: 'id', index: 'id', width: 0, align: 'center', hidden: true},
            {name: 'createAccountId', index: 'id', width: 0, align: 'center', hidden: true},
            {name: 'name', index: 'name', width: 0, align: 'center'},
            {name: 'nameCn', index: 'nameCn', width: 0, align: 'center'},
            {name: 'databaseCode', index: 'databaseCode', width: 0, align: 'center'},
            {name: 'createAccount', index: 'createAccount', width: 0, align: 'center'},
            {name: 'modifyAccount', index: 'modifyAccount', width: 0, align: 'center'},
            {name: 'createTime', index: 'createTime', width: 0, align: 'center'},
            {name: 'modifyTime', index: 'modifyTime', width: 0, align: 'center'},
            {name: 'remark', index: 'remark', width: 0, align: 'center'}
        ]
    };

    /**
     * 获取当前登录用户的id
     */
    function getCurAccountId() {
        return accountId;
    }

    /**
     * 获取翻译反转的枚举值
     * @param enumMap
     * @param key
     * @param value
     * @returns
     */
    function getTrDatas(enumMap, key, value) {
        var arr = enumMap.get(key);
        var result = '';
        $.each(arr, function (i, val) {
            if (value == val.enumValue) {
                result = val.enumCode;
                return false;
            }
        });
        return result;
    }

    return {
        init: function () {

            sUtils.select2Enum({
                selector: '#dbCode',
                enums: enumMap.get('pdm_database-databaseCode'),
                addAll: true
            });

            database.searchDatabase(true);
            database.searchDatabase(false);

            sUtils.formValidClass(databaseSearchFormSeletor);
        },

        searchDatabase: function (flag) {
            slog.log("查找数据库");
            if (flag) {

                sGrid.jqgridSimple(dbGridSetting);
                sGrid.jqgridReSize(dbGridSetting);
                sGrid.jqgridNotButton(dbGridSetting['gridId'], dbGridSetting['pagerId']);
                sGrid.jqgridDestory(dbGridSetting['gridId']);

            } else {
                var params = sUtils.getFormParams(databaseSearchFormSeletor);
                slog.log(params);

                var url = action + "database/findDatabase";
                sPost.ajaxFind(url, params, function (data) {
                    if (data.success) {
                        slog.log("Find Method 成功！");
                        params = data.obj;
                        slog.log(params);

                        sUtils.transactionEnum(params, enums, enumMap);

                        $(databaseTableSeletor).clearGridData();
                        if (params != null) {
                            $(databaseTableSeletor).setGridParam({data: params});
                        }
                        $(databaseTableSeletor).trigger("reloadGrid");
                    } else {
                        slog.error("find Method Error : " + data.msg);
                    }
                });
            }
        },

        /*
         删除数据库
         */
        delDatabase: function () {
            slog.log("database delete");
            /*
             判断是否选中
             二次确认
             */
            // 获取选中行id
            var id = $(databaseTableSeletor).jqGrid('getGridParam', 'selrow');
            // 根据id获取选中行数据
            var resData = $(databaseTableSeletor).jqGrid('getRowData', id);
            // 判断是否选中
            if (sUtils.isNull(id)) {
                layer.alert('请选择要删除的数据库！', {icon: 5, title: '提示'});
                return;
            }
            slog.log(resData);
            layer.confirm('确定要删除数据库 ' + resData.name + ' 吗？', {icon: 3, title: '提示'}, function (index) {

                var delUrl = url + resData.id;
                slog.log(delUrl);

                sPost.ajaxDel(delUrl, {}, function (data) {
                    if (data.success) {
                        slog.log("Delete Method 成功！");
                        slog.log(data);

                        $(databaseTableSeletor).jqGrid('delRowData', id);
                        layer.alert('删除成功！', {icon: 1, title: '提示'});
                    } else {
                        slog.error("Delete Method Error : " + data.msg);
                        layer.alert('删除失败！', {icon: 5, title: '提示'});
                    }
                });

                layer.close(index);
            });
        },

        /*
         数据库管理增加或修改数据库
         */
        openWinDbAddOrEdit: function (flag) {

            function initEnum() {
                sUtils.select2Enum({
                    selector: '#addDbCode',
                    enums: enumMap.get('pdm_database-databaseCode')
                });
            }

            /* 清空弹窗表单  */
            function cleanOpenWin() {
                sUtils.cleanFrom(databaseAddOrEditFormSelector);
                sUtils.validResetForm(databaseAddOrEditFormSelector);
                //如果有特殊控件，还需要特殊处理；
            }

            /*
             加载表单数据
             */
            function initOpenWin(data) {
                sUtils.setFrom(databaseAddOrEditFormSelector, data);
                $('#addDbCode').select2('val', getTrDatas(enumMap, 'pdm_database-databaseCode', data['databaseCode']));
                $('#remark').val(data.remark);
            }

            cleanOpenWin();
            initEnum();

            if (!flag) { //
                /*
                 判断是否选中行
                 获取修改的数据，填充打表单里
                 */
                // 获取选中行id
                var id = $(databaseTableSeletor).jqGrid('getGridParam', 'selrow');
                slog.log(id);

                // 判断是否选中
                if (sUtils.isNull(id)) {
                    layer.alert('请选择要修改的数据库！', {icon: 5, title: '提示'});
                    return;
                }

                var data = $(databaseTableSeletor).jqGrid('getRowData', id);
                initOpenWin(data);
            }

            var title = flag ? '新增' : '修改';
            // layer弹窗按钮
            var at = layer.open({
                type: 1,
                title: title,
                shadeClose: true,
                //shade: 0.8,
                area: ['600px', '350px'],
                content: $(databaseAddModalSelector),
                zIndex: 1000,
                btn: ['保存', '取消'],
                yes: function () {
                    var result = database.addOrEditDatabase(flag);
                    if (result == true) {
                        layer.close(at);
                    }
                }
            });
        },

        addOrEditDatabase: function (flag) {

            var url = action + 'database/';
            var params = sUtils.getFormParams(databaseAddOrEditFormSelector);
            var result = false;

            if ($(databaseAddOrEditFormSelector).valid()) {
                result = true;
                if (flag) {
                    slog.log("新增: ");
                    params.createAccountId = getCurAccountId();
                    params.modifyAccountId = getCurAccountId();
                    params.versionId = DEFAULT_VERSION_ID;

                    sPost.ajax(url, params, function (data) {
                        if (data.success) {
                            slog.log("Add Method 成功！");
                            slog.log(data);
                            database.searchDatabase(false);
                            layer.alert('新增成功！', {icon: 1, title: '提示'});
                        } else {
                            slog.error("Add Method 失败 : " + data.msg);
                            layer.alert('新增失败！' + data.msg, {icon: 5, title: '提示'});
                            result = false;
                        }
                    });

                } else {
                    params.modifyAccountId = getCurAccountId();
                    slog.log("修改参数");
                    slog.log(params);
                    sPost.ajaxPut(url, params, function (data) {
                        if (data.success) {
                            slog.log("Put Method 成功！");
                            database.searchDatabase(false);
                            layer.alert('修改成功！', {icon: 1, title: '提示'});
                        } else {
                            slog.error("Put Method Error : " + data.msg);
                            layer.alert('修改失败！' + data.msg, {icon: 5, title: '提示'});
                            result = false;
                        }
                    });
                }
            }
            return result;
        },

        /*
         * 清空数据库查询条件
         */
        clearDbSearchFrom: function () {
            slog.log("清空");
            sUtils.cleanFrom(databaseSearchFormSeletor);
            $('#dbCode').select2('val', '');
            $('#databaseVersion').val(DEFAULT_VERSION_ID);
            database.searchDatabase(false);
        }
    }
}();
